package com.idormy.sms.forwarder.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.media.MediaRecorder
import androidx.core.app.ActivityCompat
import kotlinx.coroutines.delay
import java.io.File
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class AudioRecorderUtils(private val context: Context) {

    companion object {
        private const val TAG = "AudioRecorderUtils"
        private const val DEFAULT_DURATION = 30 // 默认录音30秒
    }

    private var mediaRecorder: MediaRecorder? = null

    suspend fun recordAudio(durationSeconds: Int = DEFAULT_DURATION): File? = suspendCoroutine { continuation ->
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "Audio recording permission not granted")
            continuation.resume(null)
            return@suspendCoroutine
        }

        try {
            val outputFile = File(context.cacheDir, "audio_${System.currentTimeMillis()}.m4a")

            mediaRecorder = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                MediaRecorder(context)
            } else {
                @Suppress("DEPRECATION")
                MediaRecorder()
            }

            mediaRecorder?.apply {
                setAudioSource(MediaRecorder.AudioSource.MIC)
                setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
                setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
                setAudioEncodingBitRate(128000)
                setAudioSamplingRate(44100)
                setOutputFile(outputFile.absolutePath)

                try {
                    prepare()
                    start()
                    Log.d(TAG, "Recording started, duration: ${durationSeconds}s")

                    // 使用 Handler 延迟来控制录音时长
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        stopRecording()
                        
                        if (outputFile.exists() && outputFile.length() > 0) {
                            Log.d(TAG, "Recording completed: ${outputFile.absolutePath}")
                            continuation.resume(outputFile)
                        } else {
                            Log.e(TAG, "Recording file is empty or not found")
                            continuation.resume(null)
                        }
                    }, durationSeconds * 1000L)
                } catch (e: Exception) {
                    Log.e(TAG, "Error during recording: ${e.message}")
                    stopRecording()
                    outputFile.delete()
                    continuation.resume(null)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error initializing recorder: ${e.message}")
            e.printStackTrace()
            stopRecording()
            continuation.resume(null)
        }
    }

    private fun stopRecording() {
        try {
            mediaRecorder?.apply {
                stop()
                release()
            }
            mediaRecorder = null
            Log.d(TAG, "Recording stopped")
        } catch (e: Exception) {
            Log.e(TAG, "Error stopping recording: ${e.message}")
            mediaRecorder?.release()
            mediaRecorder = null
        }
    }

    fun release() {
        stopRecording()
    }
}
